package main

import (
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
	"path"
	"path/filepath"
)

func main() {
	// Logging to a file.
	logDir := "/var/log/gin/"
	logFile, err := filepath.Abs(path.Join(logDir, "gin.log"))
	if err != nil {
		log.Fatal(err)
	}
	err = os.MkdirAll(logDir, 0755)
	if err != nil && !os.IsExist(err) {
		log.Fatal(err)
	}
	f, err := os.Create(logFile)
	if err != nil {
		log.Fatal(err)
	}
	gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
	_, err = gin.DefaultWriter.Write([]byte("[GIN-debug] [WARNING] log file path: " + logFile + "\n"))
	if err != nil {
		log.Fatal(err)
	}
	r := gin.Default()
	hostname, err := os.Hostname()
	if err != nil {
		log.Fatalln(err)
	}
	r.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "Welcome to home page! I am " + hostname,
		})
	})
	r.GET("/hello", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message": "hello, I am " + hostname,
		})
	})
	err = r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
	if err != nil {
		log.Fatalln(err)
	}
}
